#include<stdio.h>

#include "cpu/register.h"
#include "cpu/mmu.h"
#include "memory/instruction.h"
#include "memory/dram.h"
#include "disk/elf.h"


int main(){

    //注册函数表，初始化函数指针数组
    init_handler_table();

    //init 初始化寄存器的值，初始化成gdb状态的寄存器的值
    reg.rax = 0x12340000;
    reg.rbx = 0x0;
    reg.rcx = 0x800660;
    reg.rdx = 0xabcd;
    reg.rsi = 0x7ffffffee2f8;
    reg.rdi = 0x1;
    reg.rbp = 0x7ffffffee210;
    reg.rsp = 0x7ffffffee1f0; 

    //将rip指到函数初始调用的地方
    reg.rip = (uint64_t)&program[11];

    write64bits_dram(va2pa(0x7ffffffee210), 0x08000660);//rbp
    write64bits_dram(va2pa(0x7ffffffee208), 0x1234abcd);
    write64bits_dram(va2pa(0x7ffffffee200), 0xabcd);
    write64bits_dram(va2pa(0x7ffffffee1f8), 0x12340000);
    write64bits_dram(va2pa(0x7ffffffee1f0), 0x08000660);//rsp


    print_register();
    print_stack();

    //run inst 执行指令，一共有15条指令，由rip来控制指令的依次调度
    for (int i = 0; i < 15; i++)
    {
        instruction_cycle();
        
        print_register();
        print_stack();
    }
    
    //verify 比对模拟器中寄存器的值是否和gdb中寄存器的值是否一致

    int match = 1;
    match = match && (reg.rax == 0x1234abcd);
    match = match && (reg.rbx == 0x0);
    match = match && (reg.rcx == 0x8000660);
    match = match && (reg.rdx == 0x12340000);
    match = match && (reg.rsi == 0xabcd);
    match = match && (reg.rdi == 0x12340000);
    match = match && (reg.rax == 0x7ffffffee210);
    match = match && (reg.rax == 0x7ffffffee1f0);
    if (match==1)
    {
        printf("register match\n");
    }else{
        printf("register not match\n");
    }
    
    //verify 比对内存的值是否一致
    match = match && (read64bits_dram(va2pa(0x7ffffffee210)) == 0x08000660);    //rbp
    match = match && (read64bits_dram(va2pa(0x7ffffffee208)) == 0x1234abcd);
    match = match && (read64bits_dram(va2pa(0x7ffffffee200)) == 0xabcd);
    match = match && (read64bits_dram(va2pa(0x7ffffffee1f8)) == 0x12340000);
    match = match && (read64bits_dram(va2pa(0x7ffffffee1f0)) == 0x08000660);    //rsp
    if (match==1)
    {
        printf("memory match\n");
    }else{
        printf("memory not match\n");
    }

    // reg.rax=0x1234abcd5678ffaa;

    // printf("eax:%08x\n", reg.eax);//08是print的时候显示8位，后面依次类推
    // printf("ax:%04x\n", reg.ax);
    // printf("al:%02x\n", reg.al);
    // printf("ah:%02x\n", reg.ah);

    return 0;

}

